package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.dao.RoleDao;
import com.moyuer.bsf.domain.dao.UserRoleDao;
import com.moyuer.bsf.domain.model.HqlArgs;
import com.moyuer.bsf.domain.model.Role;
import com.moyuer.bsf.domain.model.UserRoles;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.yunland.shop.domain.dao.JobPrizeDao;
import tech.yunland.shop.domain.model.JobPrize;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职位提成
 *
 * @author 王东阳<350456985@qq.com>
 */
@Service
public class JobPrizeService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JobPrizeDao jobPrizeDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    private static final String UPDATE_JOBPRIZE_HQL = "update JobPrize jp set jp.state=-1 where jp.job.id=?";

    /**
     * 保存修改
     *
     * @param jobPrize
     */
    public void saveOrUpdate(JobPrize jobPrize) {

        if (jobPrize != null) {
            jobPrizeDao.bulkUpdate(UPDATE_JOBPRIZE_HQL, jobPrize.getJob().getId());
        }
        jobPrizeDao.saveOrUpdate(jobPrize);
    }

    /**
     * 根据 id 获取职位名称(用于savelog)
     *
     * @param id
     * @return
     */
    public String getJobName(String id) {
        Role role = roleDao.get(id);
        return role.getName();
    }

    /**
     * 根据 id 获取 jobprize
     *
     * @param id
     * @return
     */
    public JobPrize get(String id) {
        return jobPrizeDao.get(id);
    }

    /**
     * 根据 id 标记删除
     *
     * @param id
     */
    @Transactional
    public void delJobPrize(String id) {
        JobPrize jobPrize = jobPrizeDao.get(id);
        if (jobPrize.getState() == -1) {
            throw new RuntimeException("已经删除");
        } else {
            jobPrize.setState(-1);
        }

        jobPrizeDao.saveOrUpdate(jobPrize);
    }

    /**
     * 根据参数生成 hql 查询语句
     *
     * @param creatorId
     * @return
     */
    public HqlArgs genHqlArgs(String creatorId, Integer state, String organId) {

        Map<String, Object> args = new HashMap<String, Object>();

        String hql = "from JobPrize jp where jp.job.state=1";
        if (creatorId != null) {
            hql += " and jp.creatorId = :creatorId";
            args.put("creatorId", creatorId);
        }

        if (state != null) {
            hql += " and jp.state = :state";
            args.put("state", state);
        }

        if (organId != null) {
            hql += " and jp.organId = :organId";
            args.put("organId", organId);
        }

        return new HqlArgs(hql, args);
    }

    /**
     * 根据入参查询结果数量
     *
     * @param creatorId
     * @return
     */
    public int getResultSize(String creatorId, Integer state, String organId) {
        HqlArgs hqlArgs = genHqlArgs(creatorId, state, organId);
        return (int) jobPrizeDao.getCount(hqlArgs.getHql(), hqlArgs.getArgs());
    }

    /**
     * 根据入参查询结果集
     *
     * @param creatorId
     * @param startIndex
     * @param length
     * @return
     */
    public List<JobPrize> getResultInfo(String creatorId, Integer state, Integer startIndex, Integer length,
                                        String organId) {
        HqlArgs hqlArgs = genHqlArgs(creatorId, state, organId);
        String hql = "select jp " + hqlArgs.getHql() + " order by jp.createTime desc";

        return jobPrizeDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
    }

    /**
     * 根据条件生成 hql 语句
     *
     * @param organId
     * @param params
     * @return
     */
    public HqlArgs genJobHql(List<String> organId, String params) {

        Map<String, Object> args = new HashMap<String, Object>();
        String hql = "select ur from UserRoles ur where 1=1 ";
        hql += " and exists ( from JobPrize jp where jp.job.id = ur.role.id) ";
        if (organId != null && organId.size() > 0) {
            if (organId.size() == 1){
                hql += " and ur.role.organ.id = :organId";
                args.put("organId", organId.get(0));
            }else {
                hql += " and ur.role.organ.id in :organId";
                args.put("organId", organId);
            }
        }
        if (StringUtils.isNotBlank(params)) {
            hql += " and ur.user.name LIKE :param OR ur.user.remark LIKE :param OR ur.user.spell LIKE :param";
            args.put("param", "%" + params + "%");
        }
        return new HqlArgs(hql, args);
    }

    /**
     * 根据入参查询结果数量
     *
     * @param organId
     * @param params
     * @return
     */
    public int getJobSize(List<String> organId, String params) {
        HqlArgs hqlArgs = genJobHql(organId, params);
        return userRoleDao.findByNamedParam(hqlArgs.getHql(), hqlArgs.getArgs()).size();
    }

    /**
     * 根据入参查询结果集
     *
     * @param organId
     * @param params
     * @param strartIndex
     * @param lenth
     * @return
     */
    public List<UserRoles> getJobInfo(List<String> organId, String params, Integer strartIndex, Integer lenth) {
        HqlArgs hqlArgs = genJobHql(organId, params);
        String hql = hqlArgs.getHql() + " order by ur.user.name";
        return userRoleDao.findByNamedParam(hql, strartIndex, lenth, hqlArgs.getArgs());
    }

    public List<Role> getRole(List<String> organId) {

        String oids = StringUtils.join(organId,"','");

        Map<String, Object> args = new HashMap<String, Object>();
        String hql =
                "SELECT\n" +
                "  br\n" +
                "FROM Role br\n" +
                "WHERE\n" +
                "  organ_id in ('"+ oids +"')\n" +
                "  AND state = '1'\n" +
                "  AND br.id NOT IN (\n" +
                "    SELECT br.id\n" +
                "    FROM\n" +
                "      JobPrize jp\n" +
                "      , Role br\n" +
                "    WHERE\n" +
                "      jp.organId in ('"+ oids +"')\n" +
                "      AND jp.job.id = br.id\n" +
                "      AND br.state = '1'\n" +
                "      AND jp.state = '1'\n" +
                "  )";
        args.put("organId", organId);
        return roleDao.find(hql);
    }
}
